#使用opencv 将黑色背景替换为白色背景
import cv2
import numpy as np
import os

import cv2
import numpy as np

# def change_background(img_path, save_path):
#     # Load the image
#     img = cv2.imread(img_path)

#     # Find black pixels and change them to white
#     img[np.where((img == [0,0,0]).all(axis = 2))] = [255,255,255]

#     # Save the result
#     cv2.imwrite(save_path, img)


def return_transparent(img_path, save_path):
    # Load the image
    img = cv2.imread(img_path)

    # Check if the image has an alpha channel
    if img.shape[2] == 3:
        # If not, convert the image to RGBA
        img = cv2.cvtColor(img, cv2.COLOR_BGR2BGRA)

    # Find black pixels and make them transparent
    #将白色变为透明
    for i in range(img.shape[0]):
        for j in range(img.shape[1]):
            if img[i,j,0] > 200 and img[i,j,1] > 200 and img[i,j,2] > 200:
                img[i,j,3] = 0
    # Save the result
    cv2.imwrite(save_path, img)


def change_background(img_path, save_path):
    # Load the image
    img = cv2.imread(img_path)
    # gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    # dilated = cv2.dilate(gray, 5)

    # Find black pixels and change them to white
    for i in range (img.shape[0]):
        for j in range (img.shape[1]):
            if img[i,j,0] < 30 and img[i,j,1] < 30 and img[i,j,2] < 30:
                img[i,j] = [255,255,255]
            elif img[i,j,0] > 200 and img[i,j,1] > 200 and img[i,j,2] > 200:
                img[i,j] = [0,0,0]

    # Save the result
    cv2.imwrite(save_path, img)
    return img

if __name__ == "__main__":
    img_path =r"plot_deepac/lines/3_white.png"
    save_path = img_path.replace(".png", "_trans.png")
    # save_path = img_path.replace(".png", "_white.png")
    # change_background(img_path, save_path)
    return_transparent(img_path, save_path)

# import cv2
# import numpy as np

# def change_background(img_path, save_path):
#     # Load the image
#     img = cv2.imread(img_path)

#     # Check if the image has an alpha channel
#     if img.shape[2] == 3:
#         # If not, convert the image to RGBA
#         img = cv2.cvtColor(img, cv2.COLOR_BGR2BGRA)

#     # Find black pixels and make them transparent
#     for i in range(img.shape[0]):
#         for j in range(img.shape[1]):
#             if img[i,j,0] < 50 and img[i,j,1] < 50 and img[i,j,2] < 50:
#                 img[i,j,3] = 0

#     # Find white pixels  and make them black
#     for i in range(img.shape[0]):
#         for j in range(img.shape[1]):
#             if img[i,j,0] > 200 and img[i,j,1] > 200 and img[i,j,2] > 200:
#                 img[i,j,0] = 0
#                 img[i,j,1] = 0
#                 img[i,j,2] = 0

#     # 将白色边缘变为黑色 寻找 边缘像素
    


#     # Save the result
#     cv2.imwrite(save_path, img)

# if __name__ == "__main__":
#     img_path =r"mask/coordin.png"
#     save_path = img_path.replace(".png", "_transparent.png")
#     change_background(img_path, save_path)